<template>
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="'80%'"
      :top="'10px'"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
      class="resourceDialog"
    >
      <div class="layui-row" style="margin-bottom: 20px">
        <p class="slip-edit resourceDialog-p">维修范围</p>
        <PageFilter :filter-list="maintainFilterInfo.list"> </PageFilter>
        <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
          <dialog-table
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            ref="resourceTable"
            v-model:data="tableInfo.data"
            :listen-height="false"
            :pager="false"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            :highlight-row="highlightRow"
            :check-box="false"
            :tabIndex="true"
            :isRowClickSelect="true"
            :max-height="350"
          >
            <template v-slot:col-deptName="scope">
              <el-form-item :prop="`data.${scope.$index}.deptName`">
                <el-input
                  v-model="scope.row.deptName"
                  class="not-br not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openDeptWindow(scope.$index)"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </template>
            <template v-slot:col-depotName="scope">
              <el-form-item :prop="`data.${scope.$index}.depotName`">
                <el-input
                  v-model="scope.row.depotName"
                  class="not-br not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择仓库"
                >
                  <template #append>
                    <el-icon @click="openDepotWindow(scope.$index)"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </template>
            <template v-slot:col-assetClassifyName="scope">
              <el-form-item :prop="`data.${scope.$index}.assetClassifyName`">
                <el-input
                  v-model="scope.row.assetClassifyName"
                  class="not-br not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择资产分类"
                >
                  <template #append>
                    <el-icon @click="openAssetClassifyWindow(scope.$index)"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </template>
          </dialog-table>
        </el-form>
      </div>
      <div class="layui-row" style="margin-bottom: 20px">
        <p class="slip-edit resourceDialog-p">范围外额外资产</p>
        <page-filter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
        >
          <template v-slot:filter-removeAsset>
            <el-button
              :disabled="!assetTableInfo.selections.length"
              @click="removeAsset"
              >删除</el-button
            >
          </template>
        </page-filter>
        <dialog-table
          :refresh="assetTableInfo.refresh"
          :init-curpage="assetTableInfo.initCurpage"
          ref="assetTable"
          v-model:data="assetTableInfo.data"
          :listen-height="false"
          :pager="false"
          :query="filterInfo.query"
          :field-list="assetTableInfo.fieldList"
          :handle="assetTableInfo.handle"
          :highlight-row="highlightRow"
          :checked-list="defaultList"
          :checkedKey="assetTableInfo.checkedKey"
          :check-box="true"
          :tabIndex="true"
          :isRowClickSelect="true"
          :max-height="350"
          @handleEvent="handleEventAsset"
        >
        </dialog-table>
      </div>
      <div class="layui-row">
        <p class="slip-edit resourceDialog-p">非资产卡片维修范围</p>
        <PageFilter :filter-list="noAssetFilterInfo.list"> </PageFilter>
        <el-form
          :model="noAssetTableInfo"
          ref="noAssetTableForm"
          style="width: 100%"
        >
          <dialog-table
            :refresh="noAssetTableInfo.refresh"
            :init-curpage="noAssetTableInfo.initCurpage"
            ref="resourceTable"
            v-model:data="noAssetTableInfo.data"
            :listen-height="false"
            :pager="false"
            :field-list="noAssetTableInfo.fieldList"
            :handle="noAssetTableInfo.handle"
            :highlight-row="highlightRow"
            :check-box="false"
            :tabIndex="true"
            :isRowClickSelect="true"
            :max-height="350"
          >
            <template v-slot:col-deptName="scope">
              <el-form-item
                :prop="`data.${scope.$index}.deptName`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          message: '请选择部门',
                          required: true,
                          trigger: 'change',
                        },
                      ]
                    : []
                "
              >
                <el-input
                  v-model="scope.row.deptName"
                  class="not-br not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openDeptWindowForNoAsset(scope.$index)"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </template>
            <template v-slot:col-notAssetRepairTypes="scope">
              <el-form-item
                :prop="`data.${scope.$index}.notAssetRepairTypes`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          message: '请选择维修类别',
                          required: true,
                          trigger: 'change',
                        },
                      ]
                    : []
                "
              >
                <selectModel
                  v-model="scope.row.notAssetRepairTypes"
                  type-code="not_asset_repair_type"
                  :clearable="false"
                  :multiple="true"
                  :checkDefault="false"
                  :collapseTags="false"
                />
              </el-form-item>
            </template>
          </dialog-table>
        </el-form>
      </div>
    </page-dialog>

    <!-- 选择部门资源 -->
    <SelectResource
      v-if="selectDeptInfo.visible"
      :query="selectDeptInfo.query"
      :title="selectDeptInfo.title"
      v-model:show-dialog="selectDeptInfo.visible"
      :default-list="selectDeptInfo.defaultList[selectDeptInfo.index]"
      @callback="addDeptResourceCallback"
    />
    <SelectResource
      v-if="selectDeptForNoAssetInfo.visible"
      :query="selectDeptForNoAssetInfo.query"
      :title="selectDeptForNoAssetInfo.title"
      v-model:show-dialog="selectDeptForNoAssetInfo.visible"
      :default-list="
        selectDeptForNoAssetInfo.defaultList[selectDeptForNoAssetInfo.index]
      "
      @callback="addDeptResourceCallbackForNoAsset"
    />
    <!-- 选择仓库资源 -->
    <SelectResource
      v-if="selectDepotInfo.visible"
      :query="selectDepotInfo.query"
      :title="selectDepotInfo.title"
      v-model:show-dialog="selectDepotInfo.visible"
      :default-list="selectDepotInfo.defaultList[selectDepotInfo.index]"
      :api="selectDepotInfo.api"
      @callback="addDepotResourceCallback"
    />
    <!-- 选择资产分类资源 -->
    <SelectAssetClassIfyResource
      v-if="selectAssetClassifyInfo.visible"
      v-model:show-dialog.sync="selectAssetClassifyInfo.visible"
      :default-list="
        selectAssetClassifyInfo.defaultList[selectAssetClassifyInfo.index]
      "
      @callback="addAssetClassifyResourceCallback"
    />
    <!--资产选择-->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :highlightRow="true"
      :checkBox="true"
      :tableKey="selectAssetInfo.tableKey"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      @callback="callBackAsset"
    />
  </div>
</template>

<script setup name="groupResource">
import { getDepotAll } from '@/api/core.js'
import PageDialog from '@/components/PageDialog/index'
import DialogTable from '@/components/DialogTable/index'
import PageFilter from '@/components/PageFilter/index'
import SelectResource from './selectResource'
import SelectAssetClassIfyResource from './selectAssetClassIfyResource'
import selectAsset from '@/components/SelectAsset/index'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  defaultList: {
    type: Array,
    default: function () {
      return []
    },
  },
  id: {
    type: [String, Number],
  },
  data: {
    type: Array,
    default: function () {
      return []
    },
  },
})
const maintainFilterInfo = ref({
  list: [{ type: 'button', label: '新增行', event: add }],
})
const noAssetFilterInfo = ref({
  list: [{ type: 'button', label: '新增行', event: noAssetAdd }],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    sort: 'create_time desc',
    ...props.query,
  },
  list: [
    { type: 'button', label: '添加', event: addAsset },
    {
      type: 'slot',
      label: '删除',
      value: 'removeAsset',
    },
  ],
})
// 维修范围表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  checkedKey: 'id',
  data: [],
  fieldList: [
    { label: '部门', value: 'deptName', type: 'slot' },
    { label: '仓库', value: 'depotName', type: 'slot' },
    { label: '资产分类', value: 'assetClassifyName', type: 'slot' },
  ],
  handle: {
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: remove,
        show: true,
      },
    ],
  },
})
//范围外额外资产表格相关
const assetTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  selections: [],
  data: [],
  fieldList: [
    { label: '资产名称', value: 'assetName' },
    { label: '资产卡片号', value: 'assetCode' },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '供应商', value: 'supplierName' },
    { label: '仓库', value: 'depotName' },
    { label: '资产分类', value: 'classifyTypeValue' },
    { label: '使用部门', value: 'useDeptName' },
  ],
  handle: {
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: removeAsset,
        show: true,
      },
    ],
  },
})
// 非资产卡片维修范围表格相关
const noAssetTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  checkedKey: 'id',
  data: [],
  fieldList: [
    { label: '部门', value: 'deptName', type: 'slot' },
    { label: '维修类别', value: 'notAssetRepairTypes', type: 'slot' },
  ],
  handle: {
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: noAssetRemove,
        show: true,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = reactive({
  title: '选择资源',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      event: save,
      show: true,
    },
  ],
})
//部门资源
const selectDeptInfo = reactive({
  visible: false,
  title: '选择部门资源',
  index: null,
  defaultList: {},
  query: {
    status: '1',
  },
})
const selectDeptForNoAssetInfo = reactive({
  visible: false,
  title: '选择部门资源',
  index: null,
  defaultList: {},
  query: {
    status: '1',
  },
})
//仓库资源
const selectDepotInfo = reactive({
  visible: false,
  title: '选择仓库资源',
  api: getDepotAll,
  index: 0,
  defaultList: {},
  query: {
    status: 1,
    useTypeId: '2',
  },
})
//资产分类资源
const selectAssetClassifyInfo = reactive({
  visible: false,
  index: 0,
  defaultList: {},
})
//通过资产档案新增
const selectAssetInfo = reactive({
  visible: false,
  tableKey: 'repairAddCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      isMaintenance: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
    },
    queryParams: {},
  },
})
const selectRow = ref('')

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})

watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      toggleSelection(val)
    }
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    if (props.data && props.data.length) {
      tableInfo.data = []
      assetTableInfo.data = []
      props.data.forEach((item, index) => {
        if (item.permissionType === 1) {
          tableInfo.data.push(item)
          let assetClassifyIds = item.assetClassifyIds
            ? item.assetClassifyIds.split(',')
            : []
          if (assetClassifyIds && assetClassifyIds.length) {
            selectAssetClassifyInfo.defaultList[index] = assetClassifyIds.map(
              (item) => Number(item)
            )
          } else {
            if (typeof item.assetClassifyIds === 'string') {
              selectAssetClassifyInfo.defaultList[index] = Number(
                item.assetClassifyIds
              )
            }
          }

          let deptIds = item.deptIds ? item.deptIds.split(',') : []
          if (deptIds && deptIds.length) {
            selectDeptInfo.defaultList[index] = deptIds.map((item) =>
              Number(item)
            )
          } else {
            if (typeof item.deptIds === 'string') {
              selectDeptInfo.defaultList[index] = Number(item.deptIds)
            }
          }
          let depotIds = item.depotIds ? item.depotIds.split(',') : []
          if (depotIds && depotIds.length) {
            selectDepotInfo.defaultList[index] = depotIds.map((item) =>
              Number(item)
            )
          } else {
            if (typeof item.depotIds === 'string') {
              selectDepotInfo.defaultList[index] = Number(item.depotIds)
            }
          }
        } else if (item.permissionType === 2) {
          assetTableInfo.data.push(item)
        } else if (item.permissionType === 3) {
          noAssetTableInfo.data.push(item)
          let deptIds = item.deptIds ? item.deptIds.split(',') : []
          if (deptIds && deptIds.length) {
            selectDeptForNoAssetInfo.defaultList[index] = deptIds.map((item) =>
              Number(item)
            )
          } else {
            if (typeof item.deptIds === 'string') {
              selectDeptForNoAssetInfo.defaultList[index] = Number(item.deptIds)
            }
          }
        }
      })
    } else if (props.id) {
      getList()
    }
  })
})

function handleEventAsset(event, data) {
  switch (event) {
    case 'tableCheck':
      assetTableInfo.selections = data
      break
  }
}
function callBackAsset(data) {
  selectAssetInfo.visible = false
  if (data && data.length) {
    assetTableInfo.data = data.concat(assetTableInfo.data)
  }
}
function addAsset() {
  //添加资产
  selectAssetInfo.query.queryMap.id.value = assetTableInfo.data
    .map((item) => item.assetId || item.id)
    .toString()
  selectAssetInfo.visible = true
}
function removeAsset(row = undefined) {
  //删除资产
  if (row && row.id) {
    assetTableInfo.data = assetTableInfo.data.filter((item) => item !== row)
  } else {
    assetTableInfo.data = assetTableInfo.data.filter(
      (row) => !assetTableInfo.selections.includes(row)
    )
  }
}
function openDeptWindowForNoAsset(index) {
  //添加部门
  selectDeptForNoAssetInfo.visible = true
  selectDeptForNoAssetInfo.index = index
  let arr = noAssetTableInfo.data[index].deptIds
    ? noAssetTableInfo.data[index].deptIds.split(',')
    : []
  selectDeptForNoAssetInfo.defaultList[selectDeptForNoAssetInfo.index] =
    arr.map((item) => {
      item = Number(item)
      return item
    })
}
function addDeptResourceCallbackForNoAsset(data) {
  //部门资源返回
  if (data && data.length) {
    noAssetTableInfo.data[selectDeptForNoAssetInfo.index]['deptName'] = data
      .map((item) => item.name)
      .toString()
    noAssetTableInfo.data[selectDeptForNoAssetInfo.index]['deptIds'] = data
      .map((item) => item.id)
      .toString()
  } else {
    noAssetTableInfo.data[selectDeptForNoAssetInfo.index]['deptName'] = ''
    noAssetTableInfo.data[selectDeptForNoAssetInfo.index]['deptIds'] = ''
  }
}
function noAssetAdd() {
  //非资产卡片维修范围-新增行
  noAssetTableInfo.data.push({
    deptName: '',
  })
}
function noAssetRemove(row) {
  //非资产卡片维修范围-删除
  noAssetTableInfo.data = noAssetTableInfo.data.filter((item) => item !== row)
}
function add() {
  //新增行
  tableInfo.data.push({
    deptName: '',
    depotName: '',
    assetClassifyName: '',
  })
}
function remove(row) {
  //删除维修范围
  tableInfo.data = tableInfo.data.filter((item) => item !== row)
}
function openDeptWindow(index) {
  //添加部门
  selectDeptInfo.visible = true
  selectDeptInfo.index = index
  let arr = tableInfo.data[index].deptIds
    ? tableInfo.data[index].deptIds.split(',')
    : []
  selectDeptInfo.defaultList[selectDeptInfo.index] = arr.map((item) => {
    item = Number(item)
    return item
  })
}
function addDeptResourceCallback(data) {
  //部门资源返回
  if (data && data.length) {
    tableInfo.data[selectDeptInfo.index]['deptName'] = data
      .map((item) => item.name)
      .toString()
    tableInfo.data[selectDeptInfo.index]['deptIds'] = data
      .map((item) => item.id)
      .toString()
  } else {
    tableInfo.data[selectDeptInfo.index]['deptName'] = ''
    tableInfo.data[selectDeptInfo.index]['deptIds'] = ''
  }
}
function openDepotWindow(index) {
  //添加仓库资源
  selectDepotInfo.visible = true
  selectDepotInfo.index = index
  let arr = tableInfo.data[index].depotIds
    ? tableInfo.data[index].depotIds.split(',')
    : []
  selectDepotInfo.defaultList[selectDepotInfo.index] = arr.map((item) => {
    item = Number(item)
    return item
  })
}
function addDepotResourceCallback(data) {
  //仓库资源返回
  if (data && data.length) {
    tableInfo.data[selectDepotInfo.index]['depotName'] = data
      .map((item) => item.name)
      .toString()
    tableInfo.data[selectDepotInfo.index]['depotIds'] = data
      .map((item) => item.id)
      .toString()
  } else {
    tableInfo.data[selectDepotInfo.index]['depotName'] = ''
    tableInfo.data[selectDepotInfo.index]['depotIds'] = ''
  }
}
function openAssetClassifyWindow(index) {
  //添加资产分类资源
  selectAssetClassifyInfo.visible = true
  selectAssetClassifyInfo.index = index
  let arr = tableInfo.data[index].assetClassifyIds
    ? tableInfo.data[index].assetClassifyIds.split(',')
    : []
  if (arr.length) {
    selectAssetClassifyInfo.defaultList[selectAssetClassifyInfo.index] =
      arr.map((item) => {
        item = Number(item)
        return item
      })
  }
}
function addAssetClassifyResourceCallback(data) {
  //资产分类资源返回
  if (data && data.length) {
    tableInfo.data[selectAssetClassifyInfo.index]['assetClassifyName'] = data
      .map((item) => item.name)
      .toString()
    tableInfo.data[selectAssetClassifyInfo.index]['assetClassifyIds'] = data
      .map((item) => item.id)
      .toString()
  } else {
    tableInfo.data[selectAssetClassifyInfo.index]['assetClassifyName'] = ''
    tableInfo.data[selectAssetClassifyInfo.index]['assetClassifyIds'] = ''
  }
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}

function save() {
  let formRefs = [proxy.$refs.tableForm, proxy.$refs.noAssetTableForm]
  proxy.$fn.checkForm(formRefs).then(() => {
    if (
      tableInfo.data &&
      tableInfo.data.length === 0 &&
      assetTableInfo.data &&
      assetTableInfo.data.length === 0 &&
      noAssetTableInfo.data &&
      noAssetTableInfo.data.length === 0
    ) {
      proxy.$message.warning('必须选择一种资源！')
      return
    }
    let resource = proxy.$fn.deepClone(tableInfo.data)
    let warnningArr = resource.filter(
      (item) => !item.depotName && !item.deptName
    )
    if (warnningArr && warnningArr.length) {
      proxy.$message.warning(
        '维修范围添加的数据行中请在部门和仓库中至少选择一个！'
      )
      return
    }
    let _warnningArr = resource.filter((item) => !item.assetClassifyName)
    if (_warnningArr && _warnningArr.length) {
      proxy.$message.warning('维修范围添加的数据行中请选择资产分类！')
      return
    }

    let data = tableInfo.data.map((item) => {
      return {
        ...item,
        permissionType: 1,
      }
    })
    let assetData = assetTableInfo.data.map((item) => {
      item.assetId = item.assetId || item.id
      return {
        ...item,
        permissionType: 2,
      }
    })
    let noAssetData = noAssetTableInfo.data.map((item) => {
      return {
        ...item,
        permissionType: 3,
      }
    })
    let params = data.concat(assetData, noAssetData)
    handleClose()
    emit('callback', params)
  })
}

// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function toggleSelection(val) {
  let rows =
    val.filter(
      (row) =>
        props.defaultList.includes(row[tableInfo.checkedKey]) || row.disabled
    ) || []
  if (rows.length) {
    proxy.$nextTick(() => {
      rows.forEach((row) =>
        proxy.$refs['resourceTable'].toggleRowSelection(row, true)
      )
    })
  }
}
</script>

<style scoped lang="scss">
.resourceDialog-p {
  font-size: 14px;
  font-weight: 600;
  padding-bottom: 10px;
}
</style>
